package com.bsj.media.init.websocket;


import org.springframework.stereotype.Component;
import org.yeauty.pojo.Session;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
public class CmdSessionCheckThread {

    private Thread thread;

    //过期时间
    private long expireTime = 5 * 60 * 1000;

    //循环次数
    private long goRunTime = 10 * 1000;

    volatile boolean isRunning = true;

    private Map<Session, Long> map = new HashMap();

    public CmdSessionCheckThread() {
        super();
    }

    public CmdSessionCheckThread(long expireTimeNow, long goRunTimeNow) {
        this.expireTime = expireTimeNow;
        this.goRunTime = goRunTimeNow;
    }

    public void push(Session session) {
        map.put(session, System.currentTimeMillis());
    }

    public void del(Session session) {
        SessionChannelUntil.del(session);
        map.remove(session);
        UserIdSessionChannelUntil.del(session);
        session.close();

    }

    public void start() {
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRunning) {
                    long t1 = System.currentTimeMillis();
                    doRun();
                    long t = System.currentTimeMillis() - t1;
                    long timeGo = goRunTime - t;
                    timeGo = timeGo > 0 ? timeGo : 0;
                    try {
                        Thread.sleep(timeGo);
                    } catch (Exception e) {

                    }
                }
            }
        });
        thread.start();
    }

    public void stop() {
        isRunning = false;
        thread.interrupt();
    }

    private void doRun() {
        if (map != null && !map.isEmpty()) {
            Set<Session> delSet = new HashSet<>();
            long now = System.currentTimeMillis();
            for (Map.Entry<Session, Long> entry : map.entrySet()) {
                Long value = entry.getValue();
                if (value == null) {
                    delSet.add(entry.getKey());
                } else {
                    long time = value;
                    long t = now - time;
                    //过期了
                    if (t > expireTime) {
                        delSet.add(entry.getKey());
                    }
                }
            }
            if (delSet != null && !delSet.isEmpty()) {
                for (Session session : delSet) {
                    del(session);
                }
            }
        }
    }
}
